package com.vote.services.impl;

import org.apache.log4j.Logger;

import java.io.Serializable;
import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.vote.services.CacheService;

public class CacheServiceMemcachedImpl implements CacheService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CacheServiceMemcachedImpl.class);
	
	private MemCachedClient memcache;
	
	private String servers;
	private String weights;
	
	public void init(){
		
		String[] serverArray = servers.split(",");
		logger.debug("start init memcached");
		SockIOPool pool = SockIOPool.getInstance();
		pool.setServers(serverArray);
		pool.setFailover(true);
		pool.setInitConn(10);
		pool.setMinConn(5);
		pool.setMaxConn(250);
		pool.setMaintSleep(30);
		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setAliveCheck(true);
		pool.initialize();
		memcache = new MemCachedClient();
		memcache.setCompressEnable(false);
		logger.debug("init memcached success!!");
		
	}
	
	public void destroy(){
		SockIOPool.getInstance().shutDown();
	}

	@Override
	public boolean exist(String key) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("check exist in cache but key == null or key = \"\".");
			return false;
		}
		return memcache.keyExists(key);
	}

	@Override
	public Object get(String key) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("get key from cache but key == null or key = \"\".");
			return null;
		}
		return memcache.get(key);
	}

	@Override
	public void remove(String key) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("remove key from cache but key == null or key = \"\".");
			return;
		}
		memcache.delete(key);
	}

	@Override
	public void set(String key, Serializable value) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("set key in cache but key == null or key = \"\".");
			return;
		}
		if(value == null){
			logger.info("set value in cache but value == null or value = \"\".");
			return;
		}
		memcache.add(key, value, new Date(defaultTimeOut));
	}

	@Override
	public void set(String key, Serializable value, long time) {
		if(key == null || "".equalsIgnoreCase(key)){
			logger.info("remove key from cache but key == null or key = \"\".");
			return;
		}
		if(value == null){
			logger.info("set value in cache but value == null or value = \"\".");
			return;
		}
		memcache.add(key, value, new Date(time));
	}

	
	public String getServers() {
		return servers;
	}

	public void setServers(String servers) {
		this.servers = servers;
	}

	public String getWeights() {
		return weights;
	}

	public void setWeights(String weights) {
		this.weights = weights;
	}

}
